package gr.uop.cst.context.adaptation;

import gr.uop.cst.context.base.Activatable;
import gr.uop.cst.context.base.ContextValueEvent;
import java.io.Serializable;

/**
 *
 * @author Ioannis Bourlakos <mi49@uop.gr>
 */
public class ContextRule implements Serializable, Activatable {

    private ContextCondition condition;
    private ContextAdaptation adaptation;
    private String stringValue; // TODO wtf
    private boolean active;

    public ContextRule(ContextCondition cond, ContextAdaptation adapt) {
        when(cond);
        then(adapt);
        this.stringValue = cond.toString() + " => " + adapt.toString();
        this.active = false;
    }
    
    public boolean isValid() {
        return this.condition.isValid();
    }

    private ContextRule when(ContextCondition cond) {
        if (cond == null) throw new NullPointerException();
        this.condition = cond;
        this.condition.addContextValueListener(new ContextConditionListener() {

            public void valueIsTrue(ContextConditionEvent evt) {
                activate();
            }

            public void valueIsFalse(ContextConditionEvent evt) {
                deactivate();
            }

            public void valueNegated(ContextConditionEvent evt) {
            }

            public void valueIsUnknown(ContextConditionEvent evt) {
            }

            public void valueRefreshed(ContextValueEvent<Boolean> evt) {
            }

            public void valueObsolete(ContextValueEvent<Boolean> evt) {
            }

            public void valueUnavailable(ContextValueEvent<Boolean> evt) {
            }

            public void valueValid(ContextValueEvent<Boolean> evt) {
            }

            public void valueRequested(ContextValueEvent<Boolean> evt) {
            }
        });
        return this;
    }

    private ContextRule then(ContextAdaptation adapt) {
        if (adapt == null) throw new NullPointerException();
        this.adaptation = adapt;
        this.adaptation.setContextRule(this);
        return this;
    }

    public ContextCondition getCondition() {
        return this.condition;
    }

    public ContextAdaptation getAdaptation() {
        return this.adaptation;
    }
    
    @Override
    public String toString() {
        return this.stringValue;
    }

    public void activate() {
        active = true;
    }

    public void deactivate() {
        active = false;
    }

    public boolean isActive() {
        return active;
    }
    
}
